import phoenixdb as pdb
import logging


# Apache Phoenix connection helper
class PhoenixConnect:
    database_url: str = 'http://localhost:8765'
    cnn = None

    def __init__(self, db_url=None):
        if db_url:
            self.database_url = db_url
            self.connect()

    def connect(self, new_url=None, autocommit=True):
        if new_url:
            self.database_url = new_url

        try:
            conn = pdb.connect(self.database_url, autocommit=autocommit)
            self.cnn = conn
        except Exception as ex:
            logging.error('连接 Phoenix 错误: ', ex)
            exit(-1)

        return self.cnn

    def close(self):
        if self.cnn:
            self.cnn.close()

    # 获取游标
    def get_update_cursor(self):
        return self.cnn.cursor()

    # 获取游标
    def get_select_cursor(self):
        return self.cnn.cursor(cursor_factory=pdb.cursor.DictCursor)

    def select(self, sql: str):
        cursor = self.get_select_cursor()
        cursor.execute(sql)
        return cursor.fetchall()
